package user

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzuser"
	"private-domain-overseas-service/tools/ent/predicate"
)

type UserDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUsersDao(ctx context.Context, svcCtx *svc.ServiceContext) *UserDao {
	return &UserDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// UserByConditionsFirst -根据条件查询单个用户
func (l *UserDao) UserByConditionsFirst(conditions []predicate.HzUser) (*ent.HzUser, error) {
	userInfo, err := l.svcCtx.Orm.HzUser.Query().Where(conditions...).First(l.ctx)
	if err != nil {
		return nil, err
	}
	return userInfo, nil
}

// UserByConditionsPages -分页查询用户信息
func (l *UserDao) UserByConditionsPages(cond []predicate.HzUser, current, pageSize int64) ([]*ent.HzUser, int, error) {
	//计算分页偏移量
	offset := common.Offset(current, pageSize)

	//查询数据
	users, err := l.svcCtx.Orm.HzUser.Query().Where(cond...).Order(ent.Desc(hzuser.FieldID)).Offset(int(offset)).Limit(int(pageSize)).All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	//统计总数
	count, err := l.svcCtx.Orm.HzUser.Query().Where(cond...).Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	return users, count, nil
}
